package cn.lblbc.album.utils

import android.content.ContentResolver
import android.content.Context
import android.provider.MediaStore
import cn.lblbc.album.model.ImageItem

object ImageLoader {
    
    fun loadImages(context: Context): List<ImageItem> {
        val images = mutableListOf<ImageItem>()
        val projection = arrayOf(
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DISPLAY_NAME,
            MediaStore.Images.Media.DATE_MODIFIED,
            MediaStore.Images.Media.SIZE
        )
        
        val sortOrder = "${MediaStore.Images.Media.DATE_MODIFIED} DESC"
        
        try {
            context.contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                sortOrder
            )?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                val dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED)
                val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)
                
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val path = cursor.getString(dataColumn)
                    val name = cursor.getString(nameColumn)
                    val dateModified = cursor.getLong(dateColumn)
                    val size = cursor.getLong(sizeColumn)
                    
                    if (path != null && name != null) {
                        images.add(ImageItem(id, path, name, dateModified, size))
                    }
                }
            }
        } catch (e: SecurityException) {
            // 处理权限不足的情况
            e.printStackTrace()
        } catch (e: Exception) {
            // 处理其他异常情况
            e.printStackTrace()
        }
        
        return images
    }
}